<template>
  <div id="sticky" :class="headerFixed?'isFixed':''">
    <div>
      <slot></slot>
    </div>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        offsetTop:'',
        headerFixed:false,
      }
    },
    mounted(){
      // this.init();
      // 监听dom渲染完成
      this.$nextTick(function(){
        // 这里fixedHeaderRoot是吸顶元素的ID
        let header = document.getElementById("sticky");
        // 这里要得到top的距离
        this.offsetTop = header.offsetTop;
        console.log("offsetTop:" + this.offsetTop);
      });

      // handleScroll为页面滚动的监听回调
      window.addEventListener('scroll', this.handleScroll);
    },
    destroyed(){
      window.removeEventListener('scroll', this.handleScroll);
    },
    methods: {
      handleScroll(){
        // 得到页面滚动的距离
        let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        // console.log(scrollTop);
        // 判断页面滚动的距离是否大于吸顶元素的位置
        this.headerFixed = scrollTop > this.offsetTop;
        // console.log(this.headerFixed);
      },
    },
  }
</script>

<style>
.isFixed{
  position: fixed;
  top: 0px;
  width: 100%;
  z-index: 100;
}
</style>
